Regular Expression Matching

Implement regular expression matching with support for ‘.’ and ‘*’.

  1. '.' Matches any single character.
  2. '*' Matches zero or more of the preceding element.
  3. The matching should cover the entire input string (not partial).
  4. The function prototype should be:
  5. bool isMatch(const char *s, const char *p)
  6. Some examples:
  7. isMatch("aa","a") false
  8. isMatch("aa","aa") true
  9. isMatch("aaa","aa") false
  10. isMatch("aa", "a*") true
  11. isMatch("aa", ".*") true
  12. isMatch("ab", ".*") true
  13. isMatch("aab", "c*a*b") true

Solution:

  1. public class Solution {
  2. public boolean isMatch(String s, String p) {
  3. int n = s.length(), m = p.length();
  4. boolean[][] dp = new boolean[n + 1][m + 1];
  5. // initialize
  6. dp[0][0] = true;
  7. for (int j = 1; j <= m; j++)
  8. dp[0][j] = j > 1 && p.charAt(j - 1) == '*' && dp[0][j - 2];
  9. for (int i = 1; i <= n; i++) {
  10. for (int j = 1; j <= m; j++) {
  11. if (p.charAt(j - 1) != '*')
  12. dp[i][j] = dp[i - 1][j - 1] && isMatch(s.charAt(i - 1), p.charAt(j - 1));
  13. else
  14. dp[i][j] = dp[i][j - 2] || dp[i - 1][j] && isMatch(s.charAt(i - 1), p.charAt(j - 2));
  15. }
  16. }
  17. return dp[n][m];
  18. }
  19. boolean isMatch(char a, char b) {
  20. return a == b || b == '.';
  21. }
  22. }